package cn.crism.chatme.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @CreateDate: 2018/12/31 5:56 PM
 * @Description:
 * @Author: Crism
 */

public class QiniuCloudUtil {

    private static final String ACCESS_KEY = "xxx";
    private static final String SECRET_KEY = "xxx";
    private static final String bucketname = "crism";
    private static final String DOMAIN = "http://cdn.crism.cn";

    public static String uploadQNImg(String filepPath, String key) {

        FileInputStream fileStream = null;
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
         try {
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(bucketname);
            try {
                fileStream = new FileInputStream(new File(filepPath));
                Response response = uploadManager.put(fileStream, key, upToken, null, null);
                DefaultPutRet putRet = JsonUtils.jsonToPojo(response.bodyString(), DefaultPutRet.class);
                String returnPath = DOMAIN + "/" + putRet.key;
                System.out.println(returnPath);
                return returnPath;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
             if (fileStream != null){
                 try {
                     fileStream.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
        return "";
    }

}
